package io.github.wanggit.antrpc.commons.generic;

import io.github.wanggit.antrpc.commons.bean.Host;
import io.github.wanggit.antrpc.commons.codec.cryption.ICodec;
import io.github.wanggit.antrpc.commons.codec.serialize.ISerializer;

import java.util.concurrent.ConcurrentHashMap;

class DefaultClients {

    private final ConcurrentHashMap<String, IClient> clients = new ConcurrentHashMap<>();
    private static final Object lock = new Object();
    private static final Object lock2 = new Object();
    private static DefaultClients instance = null;

    private DefaultClients() {}

    static DefaultClients getInstance() {
        if (null == instance) {
            synchronized (lock) {
                if (null == instance) {
                    instance = new DefaultClients();
                }
            }
        }
        return instance;
    }

    IClient getDefaultClient(Host host, ICodec codec, ISerializer serializer)
            throws InterruptedException {
        String key = host.getHostInfo();
        if (!clients.containsKey(key)) {
            synchronized (lock2) {
                if (!clients.containsKey(key)) {
                    clients.put(key, new DefaultClient(host, codec, serializer));
                }
            }
        }
        return clients.get(key);
    }
}
